package comnet.ftpclient;

import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

import javax.swing.*;
import javax.swing.text.JTextComponent;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;

/**
 * @author Mikko Puustinen (mikko.puustinen@gmail.com)
 * @version 0.1, 2007-dec-05
 */
public class MainWindow implements ChangeListener {
    private JPanel panel1;
    private JTree tree1;
    private JList mainList;
    private JTabbedPane tabbedPane1;
    private JTextComponent logTextArea;
    private JList queueList;
    private FtpClient client;
    private JPopupMenu popupmenu;

    public static void main(String[] args) {
        new MainWindow();
    }

    public MainWindow() {
        JFrame frame = new JFrame("MainWindow");
        frame.setJMenuBar(constructMenu());
        frame.add(panel1);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);

        mainList.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent me) {
                if (SwingUtilities.isLeftMouseButton(me)) {
                    int i = me.getClickCount();
                    if (i > 1) {
                        String str = (String)mainList.getSelectedValue();
                        if (str.charAt(0) == '/') {
                            client.changeDirectory(str.substring(1));
                        } else {
                            String path = JOptionPane.showInputDialog("Save file as? (e.g C:/file.txt)");
                            if (path == null) {
                                return;
                            }
                            File file = new File(path);
                            try {
                                client.downloadFile(str, file);
                            } catch (IOException e) {
                                JOptionPane.showMessageDialog(null, "Error while saving file:\n" + e.getMessage());
                            }
                        }
                    }
                }
            }
        });

        popupmenu = new JPopupMenu();
        JMenuItem menuItem = new JMenuItem("Clear...");
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                logTextArea.setText("");
            }
        });

        popupmenu.add(menuItem);
        logTextArea.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent me) {
                if (SwingUtilities.isRightMouseButton(me)) {
                    if (logTextArea.getText().length() > 0) {
                        popupmenu.show(logTextArea, me.getX(), me.getY());
                    }
                }
            }
        });
        client = new FtpClient();
        client.addChangeListenerClass(this);
    }

    public JMenuBar constructMenu() {
        JMenu fileMenu;
        JMenuBar menuBar;
        JMenuItem menuItem;

        menuBar = new JMenuBar();
        fileMenu = new JMenu("File");
        fileMenu.setMnemonic(KeyEvent.VK_F);
        menuBar.add(fileMenu);

        menuItem = new JMenuItem("Connect", KeyEvent.VK_C);
        menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F8, ActionEvent.CTRL_MASK));
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new Connect(client);
            }
        });
        fileMenu.add(menuItem);

        menuItem = new JMenuItem("Disconnect", KeyEvent.VK_D);
        menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, ActionEvent.CTRL_MASK));
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    client.close();
                    mainList.setListData(new Object[0]);
                    logTextArea.setText("");
                } catch (IOException e1) {
                    //
                }
            }
        });
        fileMenu.add(menuItem);

        menuItem = new JMenuItem("Upload file", KeyEvent.VK_S);
        menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String path = JOptionPane.showInputDialog("Location of the file? (e.g C:/file.txt)");
                File file = new File(path);
                if (file.isFile()) {
                    try {
                        client.uploadFile(file);
                        if (!client.isLastReplyPositive()) {
                            JOptionPane.showMessageDialog(null, "Error when uploading file:\n" + client.getLastServerMessage());
                        }
                    } catch (IOException e1) {
                        JOptionPane.showMessageDialog(null, "Error while uploading file:\n" + e1.getMessage());
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "File not found or path is directory");
                }
            }
        });
        fileMenu.add(menuItem);

        menuItem = new JMenuItem("Up one dir", KeyEvent.VK_U);
        menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, ActionEvent.CTRL_MASK));
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                client.upOneDirectory();
            }
        });
        fileMenu.add(menuItem);

        menuItem = new JMenuItem("Refresh file list", KeyEvent.VK_F5);
        menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, ActionEvent.CTRL_MASK));
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                changedDirectory();
            }
        });
        fileMenu.add(menuItem);

        return menuBar;
    }

    public void newServerReply() {
        String lastCode = client.getLastReply() + "\n";
        logTextArea.setText(logTextArea.getText() + lastCode);
    }

    public void changedDirectory() {
        try {
            mainList.setListData(client.getList());
        } catch (IOException e) {
            System.err.println("Mainwindow.changedDirectory: Error when fetching the list");
        }
    }

    {
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
        $$$setupUI$$$();
    }

    /**
     * Method generated by IntelliJ IDEA GUI Designer >>> IMPORTANT!! <<< DO NOT
     * edit this method OR call it in your code!
     */
    private void $$$setupUI$$$() {
        panel1 = new JPanel();
        panel1.setLayout(new FormLayout("fill:d:grow", "center:350px:grow"));
        panel1.setPreferredSize(new Dimension(535, 550));
        final JSplitPane splitPane1 = new JSplitPane();
        splitPane1.setDividerLocation(300);
        splitPane1.setOrientation(0);
        CellConstraints cc = new CellConstraints();
        panel1.add(splitPane1, cc.xy(1, 1, CellConstraints.DEFAULT, CellConstraints.FILL));
        final JSplitPane splitPane2 = new JSplitPane();
        splitPane2.setDividerLocation(0);
        splitPane1.setLeftComponent(splitPane2);
        final JScrollPane scrollPane1 = new JScrollPane();
        scrollPane1.setVisible(true);
        splitPane2.setRightComponent(scrollPane1);
        mainList = new JList();
        scrollPane1.setViewportView(mainList);
        final JScrollPane scrollPane2 = new JScrollPane();
        scrollPane2.setEnabled(false);
        scrollPane2.setVisible(false);
        splitPane2.setLeftComponent(scrollPane2);
        tree1 = new JTree();
        tree1.setEnabled(true);
        tree1.setShowsRootHandles(false);
        scrollPane2.setViewportView(tree1);
        tabbedPane1 = new JTabbedPane();
        tabbedPane1.setBackground(new Color(-2830136));
        tabbedPane1.setTabLayoutPolicy(0);
        tabbedPane1.setTabPlacement(1);
        splitPane1.setRightComponent(tabbedPane1);
        final JPanel panel2 = new JPanel();
        panel2.setLayout(new FormLayout("fill:d:grow", "center:m:grow"));
        tabbedPane1.addTab("Log", panel2);
        final JScrollPane scrollPane3 = new JScrollPane();
        panel2.add(scrollPane3, cc.xy(1, 1, CellConstraints.FILL, CellConstraints.FILL));
        logTextArea = new JTextPane();
        logTextArea.setEditable(false);
        logTextArea.setEnabled(true);
        scrollPane3.setViewportView(logTextArea);
        final JPanel panel3 = new JPanel();
        panel3.setLayout(new FormLayout("fill:d:grow", "center:d:grow"));
        tabbedPane1.addTab("Queue", panel3);
        final JScrollPane scrollPane4 = new JScrollPane();
        panel3.add(scrollPane4, cc.xy(1, 1, CellConstraints.DEFAULT, CellConstraints.FILL));
        queueList = new JList();
        queueList.setBackground(new Color(-1));
        final DefaultListModel defaultListModel1 = new DefaultListModel();
        queueList.setModel(defaultListModel1);
        scrollPane4.setViewportView(queueList);
    }

    /** @noinspection ALL */
    public JComponent $$$getRootComponent$$$() {
        return panel1;
    }
}
